<template>
  <div class="con">
    <div class="card treeDom">
      <div class="main_title">
        <i class="iconfont el-icon-zuzhi"></i>&nbsp;组织管理
      </div>
      <div slot="header" class="clearfix model-header">
        <span>部门列表</span>&nbsp;
        <i
          class="el-icon-circle-plus-outline"
          @click="addDepart"
          title="添加部门"
        ></i>
      </div>
      <el-tree
        :data="departData"
        default-expand-all
        :props="defaultProps"
        v-loading="pictLoading"
        draggable
        :allow-drag="collapse"
        :allow-drop="allowDrop"
        element-loading-text="加载中"
        accordion
        @node-drop="handleDrop"
        @node-click="handleNodeClick"
      >
        <div class="edit-node-tree" slot-scope="{ node, data }">
          <!-- 部门展示 -->
          <span class="depart-fl">
            <i
              v-show="data.grade == undefined"
              :class="data.nvr_state == 1 ? 'state' : 'statef'"
              class="iconfont"
              >&#xe631;</i
            >
            {{ node.label }}</span
          >
          <!-- 增删改操作 -->
          <span class="depart-fr">
            <el-button
              type="text"
              @click.stop
              @click="appendDepart(data)"
              v-if="data.grade <= 2"
            >
              <i
                class="el-icon-plus"
                v-if="data.grade == 2"
                title="添加设备"
              ></i>
              <i class="el-icon-plus" v-else title="添加子部门"></i>
            </el-button>
            <el-button
              v-if="!data.nvr_IMEI"
              type="text"
              @click.stop
              @click="changeDepart(data)"
            >
              <i class="el-icon-edit theme-green" title="修改"></i>
            </el-button>
            <el-button type="text" @click.stop @click="removeDepart(data)">
              <i class="el-icon-close theme-red" title="删除"></i>
            </el-button>
          </span>
        </div>
      </el-tree>
    </div>

    <dtable ref="eqmentMange" class="eqment" />

    <!--操作弹窗   S -->
    <el-dialog
      :title="dialogTitle"
      v-dialogDrag
      class="dialog-pop"
      :visible.sync="operationDialogVisible"
      width="450px"
    >
      <div class="dialog-body">
        <el-form label-position="right" label-width="100px">
          <template>
            <el-form-item :label="formLabel">
              <el-input v-model="checkdNodeInfor.title" disabled></el-input>
            </el-form-item>
            <el-form-item v-if="changeType != 3" :label="formLabel2">
              <el-input v-model="newTitle" type="text" placeholder="请输入名称">
              </el-input>
            </el-form-item>
            <el-form-item label="选择设备" v-if="changeType == 3">
              <el-select v-model="addEqumentList" multiple placeholder="请选择">
                <el-option
                  v-for="item in equmentOptions"
                  :key="item.nvr_id"
                  :label="item.nvr_name"
                  :value="item.nvr_id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="preserve()" size="small"
          >确 定</el-button
        >
        <el-button @click="operationDialogVisible = false" size="small"
          >取 消</el-button
        >
      </div>
    </el-dialog>

    <!-- 修改 -->
    <!-- 操作弹窗  E -->
  </div>
</template>

<script>
import {
  queryTree,
  addTreeNode,
  deleteNode,
  updateNodeNvr,
  noBindTree,
  updateNodeTitle,
} from "@/http";
import dtable from "@/views/DeviceManagement.vue";
export default {
  name: "Organization2",
  data() {
    return {
      departData: [], // tree数据
      defaultProps: {
        label: "title",
        value: "node_id",
      },
      operationDialogVisible: false,
      changeType: 1, // 1添加部门 2 修改部门名 3 编辑设备
      pictLoading: false, //树状图加载
      checkdNodeInfor: [], // 选中节点信息
      dialogTitle: "", // 弹窗title
      formLabel: "", // label
      formLabel2: "",
      addEqumentList: [], //添加设备列表
      equmentOptions: [], // 未添加设备
      newTitle: "", // 修改或添加新名称
      newNode: 0, // 移动后的新节点
    };
  },
  //组件
  components: {
    dtable,
  },
  //在实例创建完成后被立即调用
  created: function () {
    this.getLists();
  },

  mounted() {},
  //方法
  methods: {
    //获取未绑定设备
    queryNoBindTree() {
      noBindTree().then((res) => {
        console.log(res);
        this.equmentOptions = res.data;
      });
    },
    // 获取树状图
    getLists() {
      this.pictLoading = true;
      queryTree().then((res) => {
        this.pictLoading = false;
        this.departData = res.data;
        this.$store.commit("setTreeData", res.data);
      });
    },
    //树状操作
    handleNodeClick(data) {
      console.log(data);
    },

    //部门列表 > 添加部门
    addDepart() {
      this.checkdNodeInfor.title = "总组织";
      this.operationDialogVisible = true;
      this.changeType = 1; //1添加
    },
    //保存添加
    preserve() {
      if (this.changeType == 1) {
        addTreeNode({
          parentNode: this.checkdNodeInfor.node_id
            ? this.checkdNodeInfor.node_id
            : 0,
          title: this.newTitle,
        }).then((res) => {
          res.result_code == 200
            ? (() => {
                this.$message.success("添加成功!");
                this.getLists();
                this.operationDialogVisible = false;
              })()
            : "";
        });
      } else if (this.changeType == 2) {
        //编辑节点名称
        if (this.newTitle) {
          updateNodeTitle({
            node_id: this.checkdNodeInfor.node_id,
            title: this.newTitle,
          }).then((res) => {
            res.result_code == 200
              ? (() => {
                  this.$message.success("修改成功!");
                  this.getLists();
                  this.operationDialogVisible = false;
                })()
              : this.$message.warning("修改失败!");
          });
        } else {
          this.$message.warning("请输入新名称");
        }
      } else {
        this.updateNvr(this.addEqumentList, this.checkdNodeInfor.node_id);
      }
    },
    //弹窗展示
    showDeparParent(data) {
      this.checkdNodeInfor = data;
      this.operationDialogVisible = true;
    },
    //添加部门
    appendDepart(data) {
      data.grade > 1
        ? (this.showDeparParent(data),
          (this.changeType = 3),
          this.queryNoBindTree())
        : (() => {
            this.changeType = 1;
            this.showDeparParent(data);
          })();
    },
    //修改部门名称
    changeDepart(data) {
      this.changeType = 2;
      this.showDeparParent(data);
    },
    //删除部门提示框
    removeDepart(data) {
      this.checkdNodeInfor = data;
      if (data.nvr_IMEI) {
        this.$confirm("确定从当前组织删除改设备?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
        }).then(() => {
          //删除设备
          this.delNode(1);
        });
      } else if (!data.children || data.children.length < 1) {
        this.$confirm("确定删除该部门?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
        }).then(() => {
          //删除组织
          this.delNode(2);
        });
      } else {
        this.$message({
          message: "当前组织下有其它组织或设备,请清除后再试?",
          type: "error",
          showClose: true,
        });
      }
    },
    //删除该部门
    delNode(val) {
      val == 2
        ? deleteNode({ node_id: this.checkdNodeInfor.node_id }).then((res) => {
            res.result_code == 200
              ? (this.$message.success("删除节点成功!"), this.getLists())
              : this.$message.warning("删除节点失败!");
          })
        : this.updateNvr([this.checkdNodeInfor.node_id], this.newNode);
    },
    updateNvr(nvr_id, respectiveRegional) {
      updateNodeNvr({
        nvr_id,
        respectiveRegional,
      }).then((res) => {
        res.result_code == 200
          ? (this.$message.success("设备修改成功!"),
            this.getLists(),
            (this.addEqumentList = []),
            (this.operationDialogVisible = false))
          : this.$message.warning("修改失败!");
      });
    },

    //拖动结束
    handleDrop(data, newNode, inner) {
      console.log(data, newNode, inner);
      data.parent
        ? (() => {
            if (data.parent.id != newNode.id) {
              if (inner == "inner") {
                this.updateNvr([data.data.node_id], newNode.data.node_id);
              } else if (inner == "before") {
                this.updateNvr(
                  [data.data.node_id],
                  newNode.parent.data.node_id
                );
              }
            }
          })()
        : (() => {
            if (inner == "inner") {
              this.updateNvr([data.data.node_id], newNode.data.node_id);
            } else if (inner == "before") {
              this.updateNvr([data.data.node_id], newNode.parent.data.node_id);
            }
          })();
    },
    // 限制某些节点可以拖拽
    collapse(moveNode) {
      if (moveNode.data.nvr_IMEI) {
        return true;
      }
    },
    // 判断节点能否被放置
    allowDrop(moveNode, inNode, type) {
      if (inNode.level == 1) {
        return false;
      } else if (
        (inNode.level == 3 || inNode.level == 2) &&
        !inNode.data.nvr_IMEI
      ) {
        return type === "inner";
      }
      if (inNode.data.nvr_IMEI) {
        return type === "prev";
      }
    },
  },
  watch: {
    operationDialogVisible: {
      handler(val) {
        !val ? ((this.checkdNodeInfor = []), (this.newTitle = "")) : "";
      },
    },
    changeType: {
      handler(val) {
        switch (val) {
          case 1:
            this.dialogTitle = "添加部门";
            this.formLabel = "当前部门";
            this.formLabel2 = "子部门名称";
            break;
          case 2:
            this.dialogTitle = "修改部门名称";
            this.formLabel = "当前名称";
            this.formLabel2 = "新名称";
            break;
          case 3:
            this.dialogTitle = "添加设备";
            this.formLabel = "当前部门";
            break;
          default:
            break;
        }
        val == 1;
      },
      immediate: true,
    },
  },
};
</script>
<style scoped>
/* .videoDome {
  width: 70%;
  height: 83.5vh;
} */
.eqment {
  width: 76%;
  float: right;
}

.card {
  width: 24%;
  height: 83.5vh;
  border: none;
  float: left;
  background: none;
  color: white;
}
.model-header {
  padding: 10px 0 15px;
  border-bottom: 1px solid #fff;
  margin-bottom: 15px;
}
.active {
  color: white;
}

.el-tree {
  background: none;
  color: white;
}
.depart-fl {
  float: left;
  height: 40px;
  line-height: 40px;
}

.depart-fr {
  position: absolute;
  right: 0;
  height: 40px;
  line-height: 40px;
  display: none;
}
.state {
  color: #1ab394;
}
.statef {
  color: #aaa;
}
.edit-node-tree {
  width: 100%;
}

.edit-node-tree:hover .depart-fr {
  display: block;
  margin-right: 14px;
}

.theme-green {
  color: #2eca56;
}

.theme-red {
  color: #ff6c87;
}
</style>
